import { DataTypes, Model, UUIDV4 } from 'sequelize';
import { get } from 'lodash';
import { getSequelize } from '../db';

// 参数值
class AppParameterValues extends Model {
  static async getAppParameterValue(hotel_id, app_parameter_name_id) {
    const data = await this.findOne({ where: { hotel_id, app_parameter_name_id } });
    return get(data, 'app_parameter_value');
  }
}

AppParameterValues.init({
  id: {
    type: DataTypes.UUID, unique: 'id', allowNull: false, defaultValue: UUIDV4, validate: { isUUID: 4 }, primaryKey: true, comment: '主键', editable: false
  },
  hotel_id: {
    type: DataTypes.UUID, allowNull: false, defaultValue: UUIDV4, validate: { isUUID: 4 }, comment: '主体id'
  },
  app_parameter_name_id: {
    type: DataTypes.STRING(80), allowNull: false, comment: '参数内部名称'
  },
  app_parameter_value: {
    type: DataTypes.STRING(200), allowNull: true, comment: '参数值'
  },
  created_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '创建用户'
  },
  updated_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '更新用户'
  },
  version: {
    type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: '版本控制'
  }
}, {
  sequelize: getSequelize(),
  tableName: 'app_parameter_values',
  comment: '应用参数值',
  indexes: [{ fields: ['hotel_id', 'app_parameter_name_id'], unique: true }]
});

AppParameterValues.associate = (models) => {
  AppParameterValues.belongsTo(models.AppParameterNames, {
    foreignKey: 'app_parameter_name_id',
    targetKey: 'id',
    as: 'app_parameter_name',
    constraints: false
  });
};

export default AppParameterValues;
